package com.algorithm;

public class DictMin {

    public String removeDuplicateLetters(String s) {
        char[] schs=s.toCharArray();
        int[] count=new int[26];
        for(char ch:schs){
            count[ch-'a']++;
        }

        StringBuilder stack=new StringBuilder();
        boolean[] visited=new boolean[26];
        for(char ch:schs){
            if (!visited[ch - 'a']) {
                while (stack.length() > 0 && peek(stack)> ch) {
                    if (count[peek(stack) - 'a'] > 0) {
                        visited[peek(stack) - 'a'] = false;
                        stack.deleteCharAt(stack.length() - 1);
                    } else {
                        break;
                    }
                }
                visited[ch - 'a'] = true;
                stack.append(ch);
            }
            count[ch - 'a'] -= 1;
        }
        return stack.toString();
    }

    char peek(StringBuilder stack){
        return peek(stack,stack.length()-1);
    }

    char peek(StringBuilder stack,int index){
        return stack.charAt(index);
    }

    public static void main(String[] args) {
        DictMin dictMin = new DictMin();
        String ret = dictMin.removeDuplicateLetters("bcabc");
        System.out.println(ret);
    }
}
